var tcppkg={
	read_pkg_size:function(pkg_data,offset)
	{
		//包的长度至少要是2个字节
		if (offset+2>pkg_data.length)
			return -1;

		var len=pkg_data.readUInt16BE(offset);
		return len;
	},

	package_data:function(data)
	{
		var buf_len=data.utf8_byte_len();
		var buf=Buffer.allocUnsafe(2+buf_len);
		buf.writeUInt16BE(buf_len,0);
		//fill可以填充字符串和二进制流
		buf.fill(data,2);

		return buf;
	},

	unpackage_data:function(data)
	{
		var tabel={remain:null,data:[]};

		var offset=0;
		var pkg_len=tcppkg.read_pkg_size(data,offset);
		if(pkg_len<0)
			return tabel;

		while(offset+pkg_len+2<=data.length)
		{
			var cmd_buf=Buffer.allocUnsafe(pkg_len);
			data.copy(cmd_buf,0,offset+2,offset+2+pkg_len);

			tabel.data.push(cmd_buf);

			offset+=pkg_len+2;

			//数据包正好处理完
			if (offset>=data.length)
				break;

			//获取下一个包的长度
			pkg_len=tcppkg.read_pkg_size(data,offset);
			if(pkg_len<0)
				break;
		}

		if (offset>=data.length){
			tabel.remain=null;
		}
		//处理还有剩余数据的情况
		else{
			var buf=Buffer.allocUnsafe(data.length-offset);
			data.copy(buf,0,offset,data.length);
			tabel.remain=buf;
		}

		return tabel;
	}

};

module.exports=tcppkg;